<template>
  <el-dialog
    :visible="value"
    :title="mode === 'add' ? '新增角色' : '修改角色'"
    @close="closeDialog"
    width="30%"
  >
    <span slot="footer" class="dialog-footer">
      <el-form :model="form" label-width="100px" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="closeDialog"> 取消</el-button>
      <el-button type="primary" @click="addRoles">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 导入新增角色的方法
import { addRole, editRole } from '@/api/setting'
export default {
  props: ['value', 'tableData'],

  data () {
    return {
      // 决定时新增还是编辑
      mode: 'add',
      // dialog组件是否显示
      isShow: false,
      // 表单数据源
      form: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              this.tableData.some(item => {
                return item.name === value
              })
                ? callback(new Error('已有此角色'))
                : callback()
            },
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹框
    closeDialog () {
      // this.isShow = false
      //   this.$emit('input', false)
      this.$emit('update:value', false)
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新增角色
    async addRoles () {
      if (this.mode === 'add') {
        const res = await addRole(this.form)
        // console.log(res)
        this.$message.success('新增成功')
        this.closeDialog()
        this.$emit('getRoleList')
      } else {
        const res = await editRole(this.form)
        console.log(res)
        this.$message.success('修改成功')
        this.closeDialog()
        this.$emit('getRoleList')
      }
    }
  }
}
</script>

<style></style>
